// pages/real_time_monitoring/real_time_monitoring.js
const db = wx.cloud.database();
const GreenHouseCollection = db.collection('Greenhouse_Data');
const wxCharts = require('../../libs/wxcharts-min');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        actions: [],
        show: false,
        loading: false,
        selectedData: null,
        normalData: [23,55,32000,750],
        useMsg:"",
    },

    onLoad() {
        this.loadData();
    },
    async loadData() {
        try {
            const res = await GreenHouseCollection.get();
            console.log(res.data);
            const newData = res.data.map(item => ({
                greenhouseID: item.greenhouseID,
                temperature: item.temperature,
                humidity: item.humidity,
                light: item.light,
                gasCO2: item['gas(CO2)'],
                monitorTime: item.monitorTime,
                video: item.video // 修正拼写错误
            }));

            this.setData({
                actions: this.data.actions.concat(newData),
            });
        } catch (e) {
            console.error('获取大棚数据失败', e);
            this.setData({
                loading: false
            });
        }
    },

    async onSelect(e) {
      this.setData({ show: true,loading:true });
      let selectedData = e.target.dataset.news;
      this.setData({
          selectedData: selectedData
      });
      console.log("selectedData", selectedData);
      let detectedData = [(selectedData.temperature / 25).toFixed(2), (selectedData.humidity / 55).toFixed(2), (selectedData.light / 32000).toFixed(2), (selectedData["gasCO2"] / 750).toFixed(2)];
      console.log("detectedData", detectedData);
  
      // 构建userMessageContent
      let userMessageContent = `我的葡萄种植大棚现在的温度是${selectedData.temperature},湿度是${selectedData.humidity},光照强度是${selectedData.light},二氧化碳浓度是${selectedData["gasCO2"]}，我需要做什么措施吗？打开通风扇，打开棚顶，打开日光灯，抽水还是什么都不要做？`;
  
      // 初始化图表
      new wxCharts({
          canvasId: 'barCanvas',
          type: 'column',
          categories: ['温度', '湿度', '光照强度', 'CO2浓度'],
          series: [
              {
                  name: '检测值',
                  data: detectedData,
                  color: '#FF6B6B',
              },
              {
                  name: '正常值',
                  data: [1, 1, 1, 1],
                  color: '#4ECDC4',
              },
          ],
          dataLabel: false,
          yAxis: {
              title: '温度',
              min: 0,
              format: function () {
                  return '';
              }
          },
          width: 350,
          height: 200,
          animation: true,
          background: '#FFF'
      });
      // 调用云函数
      this.setData({
        loading:true
      });
      wx.cloud.callFunction({
        name: 'BlueLM-70BAPI',
        data: {
            // 注意这里参数名要和云函数一致
            prompt: userMessageContent
        },
        success: res => {
            console.log('云函数调用成功', res.result.data.data);
            this.setData({
              loading:false,
              useMsg:res.result.data.data
            })
            // 这里可以根据云函数返回的结果进行进一步处理，比如显示在界面上
        },
        fail: err => {
            console.error('云函数调用失败', err);
            // 处理错误情况，比如提示用户调用失败
        }
    });
  },
    onClose() {
        this.setData({ show: false });
    },

})    